package com.jinxin.platform.cdysylives.rpc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jinxin.platform.base.api.annotation.*;
import com.jinxin.platform.base.api.constant.APCOSApiConstans;
import com.jinxin.platform.base.common.pojo.InvokeCfg;
import com.jinxin.platform.base.common.pojo.JsonResult;
import com.jinxin.platform.base.common.support.BusinessDelegate;
import com.jinxin.platform.cdysylives.bean.bo.OptionVo;
import com.jinxin.platform.cdysylives.common.Constant;
import com.jinxin.platform.cdysylives.common.SysOrganization;
import com.jinxin.platform.cdysylives.common.SysUserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

import static com.alibaba.fastjson.JSON.toJSONString;

/**
 * @Author 那个男人
 * @Date 2023/7/25 9:54
 * @Version 1.0
 */
@Component
@Slf4j
@NeedInf(moduleKey = Constant.MODULE_KEY, className = Constant.MODULE_CLASS_NAME)
public class CdysyliveRpc {
    @Autowired
    private BusinessDelegate businessDelegate;

    /**
     * 获取当前用户对象
     *
     * @return SysUser
     */
    @APCOSApiOperation(value = "getCurrentUser", description = "获取当前登录者", infDict = "获取当前登录者",
            reqDemo = "{}", respDemo = "{\"userId\":\"123\",\"userName\":\"张三\",\"userAccount\":\"13812345678\"}",
            infType = APCOSApiConstans.INF_TYPE_OTHER)
    @APCOSApiRequests({})
    @APCOSApiResponses({
            @APCOSApiResponse(name = "userAccount", value = "登录账户", dict = "登录账户",required = true,
                    keyType = APCOSApiConstans.KEY_TYPE_STR,fieldType = APCOSApiConstans.FIELD_TYPE_GN,
                    dataType = APCOSApiConstans.DATA_TYPE_STR,lenth = "50",remark = "登录账户"),
            @APCOSApiResponse(name = "userId", value = "用户ID", dict = "用户ID",required = true,
                    keyType = APCOSApiConstans.KEY_TYPE_STR,fieldType = APCOSApiConstans.FIELD_TYPE_GN,
                    dataType = APCOSApiConstans.DATA_TYPE_STR,lenth = "50",remark = "用户ID"),
            @APCOSApiResponse(name = "userName", value = "用户姓名", dict = "用户姓名",required = true,
                    keyType = APCOSApiConstans.KEY_TYPE_STR,fieldType = APCOSApiConstans.FIELD_TYPE_GN,
                    dataType = APCOSApiConstans.DATA_TYPE_STR,lenth = "50",remark = "用户姓名"),
    })
    public SysUserVO getCurrentUser() {
        JsonResult result = getJsonResult(Constant.MODULE_KEY,"getCurrentUser");
        if (result.getSuccess()) {
            if (result.getData() == null) {
                return null;
            }
            log.info("getCdys7liveCurrentUser:" + result.getData());
            return JSON.parseObject(toJSONString(result.getData()), SysUserVO.class);
        }
        else {
            SysUserVO userVO = new SysUserVO();
            userVO.setUserId("1");
            userVO.setUserAccount("admin");
            userVO.setUserName("admin");
            userVO.setUserCellphoneNo("13888881234");
            userVO.setOrgId("1");
            userVO.setOrgName("一个牛逼的公司");
            return userVO;
        }
//        return null;
    }

    private JsonResult getJsonResult(String keyName,String funName) {
        InvokeCfg cfg = new InvokeCfg();
        cfg.setModuleKey(keyName);
        cfg.setClassName(Constant.MODULE_CLASS_NAME);
        cfg.setFunName(funName);
        return businessDelegate.invoke(cfg);
    }

    @APCOSApiOperation(value = "getOrgansByPId", description = "通过父级ID查询组织", infDict = "通过父级ID查询组织",
            reqDemo = "{\"orgPid\": \"1237043565473959936\",\"containsParent\": true\n}", respDemo = "{\"data\":[{\"orgId\":\"1237043565473959936\",\"orgLevels\":\"1\",\"orgName\":\"一级组织\",\"orgPid\":\"0\"}]}",
            infType = APCOSApiConstans.INF_TYPE_OTHER)
    @APCOSApiRequests({
            @APCOSApiRequest(name = "containsParent", value = "结果是否包含父级", dict = "结果是否包含父级",matchType = APCOSApiConstans.MATCH_TYPE_EQ,
                    keyType = APCOSApiConstans.KEY_TYPE_STR,fieldType = APCOSApiConstans.FIELD_TYPE_GN,
                    dataType = APCOSApiConstans.DATA_TYPE_STR,lenth = "10",remark = "结果是否包含父级"),
            @APCOSApiRequest(name = "orgPid", value = "父级组织ID", dict = "父级组织ID",matchType = APCOSApiConstans.MATCH_TYPE_EQ,
                    keyType = APCOSApiConstans.KEY_TYPE_STR,fieldType = APCOSApiConstans.FIELD_TYPE_GN,
                    dataType = APCOSApiConstans.DATA_TYPE_STR,lenth = "50",remark = "父级组织ID"),
    })
    @APCOSApiResponses({
            @APCOSApiResponse(name = "data", value = "返回集合", dict = "返回集合",
                    keyType = APCOSApiConstans.KEY_TYPE_LIST,fieldType = APCOSApiConstans.FIELD_TYPE_GN,
                    dataType = APCOSApiConstans.DATA_TYPE_ARR,remark = "返回集合"),
            @APCOSApiResponse(name = "data.orgId", value = "组织id", dict = "组织id",
                    keyType = APCOSApiConstans.KEY_TYPE_STR,fieldType = APCOSApiConstans.FIELD_TYPE_GN,
                    dataType = APCOSApiConstans.DATA_TYPE_STR,lenth = "50",remark = "组织id"),
            @APCOSApiResponse(name = "data.orgLevels", value = "组织层级", dict = "组织层级",
                    keyType = APCOSApiConstans.KEY_TYPE_STR,fieldType = APCOSApiConstans.FIELD_TYPE_GN,
                    dataType = APCOSApiConstans.DATA_TYPE_STR,lenth = "50",remark = "组织层级"),
            @APCOSApiResponse(name = "data.orgName", value = "组织名称", dict = "组织名称",
                    keyType = APCOSApiConstans.KEY_TYPE_STR,fieldType = APCOSApiConstans.FIELD_TYPE_GN,
                    dataType = APCOSApiConstans.DATA_TYPE_STR,lenth = "50",remark = "组织名称"),
            @APCOSApiResponse(name = "data.orgPid", value = "父级id", dict = "父级id",
                    keyType = APCOSApiConstans.KEY_TYPE_STR,fieldType = APCOSApiConstans.FIELD_TYPE_GN,
                    dataType = APCOSApiConstans.DATA_TYPE_STR,lenth = "50",remark = "父级id"),
    })
    public List<SysOrganization> getOrgansByPId(String orgPid) {
        InvokeCfg cfg = new InvokeCfg();
        cfg.setModuleKey(Constant.MODULE_KEY);
        cfg.setClassName(Constant.MODULE_CLASS_NAME);
        cfg.setFunName("getOrgansByPId");
        Map<String,Object> map = new HashMap<>();
        map.put("orgPid",orgPid);
        map.put("containsParent",true);//不包括本级组织
        cfg.setArgs(map);
        JsonResult result = businessDelegate.invoke(cfg);
        log.info("getOrgansByPId: " + result.toString());
        List<SysOrganization> sysOrganizationList = new ArrayList<>();
        if (result.getSuccess()) {
            if (result.getData() == null) {
                return null;
            }
            JSONObject jsonObj = JSONObject.parseObject(result.getData().toString());
            sysOrganizationList = JSON.parseArray(jsonObj.get("data").toString(), SysOrganization.class);
            log.info("======组织集合====={}============", sysOrganizationList.toString());
            return sysOrganizationList;
        }
//        return sysOrganizationList;
//        走测试组织信息
        SysOrganization sysOrganization1 = new SysOrganization("0", "1", "3", "顶级组织名称", "0", 1583769163000L);
        SysOrganization sysOrganization2 = new SysOrganization("0", "2-1", "级别", "一级组织名称1", "1", 202112270);
        SysOrganization sysOrganization3 = new SysOrganization("0", "2-2", "级别", "一级组织名称2", "1", 202112270);
        SysOrganization sysOrganization4 = new SysOrganization("0", "2-1-1", "级别", "一级组织的二级组织名称", "2-1", 202112270);
        sysOrganizationList.add(sysOrganization1);
        sysOrganizationList.add(sysOrganization2);
        sysOrganizationList.add(sysOrganization3);
        sysOrganizationList.add(sysOrganization4);
        log.info("===========测试组织信息==========={}", sysOrganizationList);
        return sysOrganizationList;
    }

    @APCOSApiOperation(value = "getAllOrgs", description = "按条件查询组织", infDict = "按条件查询组织",
            reqDemo = "{}", respDemo = "{\"data\":[{\"orgId\":\"1237043565473959936\",\"orgLevels\":\"1\",\"orgName\":\"一级组织\",\"orgPid\":\"0\"}]}",
            infType = APCOSApiConstans.INF_TYPE_OTHER)
    @APCOSApiRequests({})
    @APCOSApiResponses({
            @APCOSApiResponse(name = "data", value = "返回集合", dict = "返回集合",
                    keyType = APCOSApiConstans.KEY_TYPE_LIST,fieldType = APCOSApiConstans.FIELD_TYPE_GN,
                    dataType = APCOSApiConstans.DATA_TYPE_ARR,remark = "返回集合"),
            @APCOSApiResponse(name = "data.orgId", value = "组织id", dict = "组织ID",
                    keyType = APCOSApiConstans.KEY_TYPE_STR,fieldType = APCOSApiConstans.FIELD_TYPE_GN,
                    dataType = APCOSApiConstans.DATA_TYPE_STR,lenth = "50",remark = "组织id"),
            @APCOSApiResponse(name = "data.orgLevels", value = "组织层级", dict = "层级",
                    keyType = APCOSApiConstans.KEY_TYPE_STR,fieldType = APCOSApiConstans.FIELD_TYPE_GN,
                    dataType = APCOSApiConstans.DATA_TYPE_STR,lenth = "50",remark = "组织层级"),
            @APCOSApiResponse(name = "data.orgName", value = "组织名称", dict = "组织名称",
                    keyType = APCOSApiConstans.KEY_TYPE_STR,fieldType = APCOSApiConstans.FIELD_TYPE_GN,
                    dataType = APCOSApiConstans.DATA_TYPE_STR,lenth = "50",remark = "组织名称"),
            @APCOSApiResponse(name = "data.orgPid", value = "父级id", dict = "上级组织名称",
                    keyType = APCOSApiConstans.KEY_TYPE_STR,fieldType = APCOSApiConstans.FIELD_TYPE_GN,
                    dataType = APCOSApiConstans.DATA_TYPE_STR,lenth = "50",remark = "父级id"),
    })
    public List<SysOrganization> getAllOrgs() {
        InvokeCfg cfg = new InvokeCfg();
        cfg.setModuleKey(Constant.MODULE_KEY);
        cfg.setClassName(Constant.MODULE_CLASS_NAME);
        cfg.setFunName("getAllOrgs");
        Map<String,String> map = new HashMap<>();
        cfg.setArgs(map);
        JsonResult result = businessDelegate.invoke(cfg);
        log.info("getAllOrgs: " + result.toString());
        List<SysOrganization> sysOrganizationList = new ArrayList<>();
        if (result.getSuccess()) {
            if (result.getData() == null) {
                return null;
            }
            JSONObject jsonObj = JSONObject.parseObject(result.getData().toString());
            sysOrganizationList = JSON.parseArray(jsonObj.get("data").toString(), SysOrganization.class);
            log.info("======所有组织集合====={}============", sysOrganizationList.toString());
            return sysOrganizationList;
        }
//        return sysOrganizationList;
        //走测试组织信息
        SysOrganization sysOrganization1 = new SysOrganization("0", "1", "3", "顶级组织名称", "0", 1583769163000L);
        SysOrganization sysOrganization2 = new SysOrganization("0", "2-1", "级别", "一级组织名称1", "1", 202112270);
        SysOrganization sysOrganization3 = new SysOrganization("0", "2-2", "级别", "一级组织名称2", "1", 202112270);
        SysOrganization sysOrganization4 = new SysOrganization("0", "2-1-1", "级别", "一级组织的二级组织名称", "2-1", 202112270);
        sysOrganizationList.add(sysOrganization1);
        sysOrganizationList.add(sysOrganization2);
        sysOrganizationList.add(sysOrganization3);
        sysOrganizationList.add(sysOrganization4);
        log.info("===========测试组织信息==========={}", sysOrganizationList);
        return sysOrganizationList;
    }

    /**
     * 查询组织管理员
     *
     * @return SysUser
     */
    @APCOSApiOperation(value = "getOrgUser", description = "查询组织管理员", infDict = "查询组织管理员",
            reqDemo = "{\"userId\":\"123\",\"orgId\":\"456\"}", respDemo = "{\"userId\":\"123\",\"userName\":\"张三\"}",
            infType = APCOSApiConstans.INF_TYPE_OTHER)
    @APCOSApiRequests({
            @APCOSApiRequest(name = "userId", value = "用户ID", dict = "用户ID",matchType = APCOSApiConstans.MATCH_TYPE_EQ,
                    keyType = APCOSApiConstans.KEY_TYPE_STR,fieldType = APCOSApiConstans.FIELD_TYPE_GN,
                    dataType = APCOSApiConstans.DATA_TYPE_STR,lenth = "50",remark = "用户ID"),
            @APCOSApiRequest(name = "orgId", value = "组织id", dict = "组织id",matchType = APCOSApiConstans.MATCH_TYPE_EQ,
                    keyType = APCOSApiConstans.KEY_TYPE_STR,fieldType = APCOSApiConstans.FIELD_TYPE_GN,
                    dataType = APCOSApiConstans.DATA_TYPE_STR,lenth = "50",remark = "组织id"),
    })
    @APCOSApiResponses({
            @APCOSApiResponse(name = "userId", value = "用户ID", dict = "用户ID",
                    keyType = APCOSApiConstans.KEY_TYPE_STR,fieldType = APCOSApiConstans.FIELD_TYPE_GN,
                    dataType = APCOSApiConstans.DATA_TYPE_STR,lenth = "50",remark = "用户ID"),
            @APCOSApiResponse(name = "userName", value = "用户姓名", dict = "用户姓名",
                    keyType = APCOSApiConstans.KEY_TYPE_STR,fieldType = APCOSApiConstans.FIELD_TYPE_GN,
                    dataType = APCOSApiConstans.DATA_TYPE_STR,lenth = "50",remark = "用户姓名"),
    })
    public SysUserVO getOrgUser(String userId,String orgId) {
        InvokeCfg cfg = new InvokeCfg();
        cfg.setModuleKey(Constant.MODULE_KEY);
        cfg.setClassName(Constant.MODULE_CLASS_NAME);
        cfg.setFunName("getOrgUser");
        HashMap<String, String> map = new HashMap<>();
        map.put("userId",userId);
        map.put("orgId",orgId);
        cfg.setArgs(map);
        log.info("查询组织管理员：{}",JSON.toJSONString(cfg));
        JsonResult result = businessDelegate.invoke(cfg);
        if (result.getSuccess()){
            log.info("getOrgUser:" + result.getData());
            return JSON.parseObject(toJSONString(result.getData()), SysUserVO.class);
        }
        else {
            SysUserVO userVO = new SysUserVO();
            userVO.setUserId("1");
            userVO.setUserAccount("admin");
            userVO.setUserName("admin");
            userVO.setUserCellphoneNo("13888881234");
            userVO.setOrgId("1");
            userVO.setOrgName("一个牛逼的公司");
            return userVO;
        }
//        return null;
    }

    private Set<String> getOrgNameArr(String orgPid){
        Set<String> orgIdList = new HashSet<>();
        List<SysOrganization> orgList;
        if(StringUtils.isEmpty(orgPid)){
            orgList = getAllOrgs();;
        }else {
            orgList = getOrgansByPId(orgPid);;
        }
        if(CollectionUtils.isEmpty(orgList)){
            return new HashSet<>();
        }
        orgList.forEach(item-> orgIdList.add(item.getOrgName()));
        return orgIdList;
    }

    public Set<String> getOrgNameSet(){
        SysUserVO currentUser = getCurrentUser();
        if(currentUser == null){
            log.info("未登录");
            return new HashSet<>();
        }
        String orgId = currentUser.getOrgId();
        if(StringUtils.isEmpty(orgId)){//获取所有
            log.info("未加入任何组织就获取所有组织");
            return getOrgNameArr(orgId);
        }else {
            String userId = currentUser.getUserId();
            SysUserVO orgUser = getOrgUser(userId, orgId);
            if(orgUser == null || !orgUser.getUserId().equals(userId)){
                log.info("不是组织管理员返回空");
                return new HashSet<>();
            }
            return getOrgNameArr(orgId);
        }
    }

    @APCOSApiOperation(value = "queryCommunityList", description = "查询社区列表", infDict = "selectList",
            reqDemo = "{}", respDemo = "{\"data\":[{\"id\":\"社区ID\",\"name\":\"社区名称\"}]}",
            infType = APCOSApiConstans.INF_TYPE_OTHER)
    @APCOSApiRequests({})
    @APCOSApiResponses({
            @APCOSApiResponse(name = "data", value = "返回集合", dict = "shequ_data",
                    keyType = APCOSApiConstans.KEY_TYPE_LIST,fieldType = APCOSApiConstans.FIELD_TYPE_GN,
                    dataType = APCOSApiConstans.DATA_TYPE_ARR,remark = "返回集合"),
            @APCOSApiResponse(name = "data.id", value = "社区id", dict = "id",
                    keyType = APCOSApiConstans.KEY_TYPE_STR,fieldType = APCOSApiConstans.FIELD_TYPE_GN,
                    dataType = APCOSApiConstans.DATA_TYPE_STR,lenth = "50",remark = "组织id"),
            @APCOSApiResponse(name = "data.name", value = "社区名称", dict = "sq_name",
                    keyType = APCOSApiConstans.KEY_TYPE_STR,fieldType = APCOSApiConstans.FIELD_TYPE_GN,
                    dataType = APCOSApiConstans.DATA_TYPE_STR,lenth = "50",remark = "社区名称"),
    })
    public JsonResult queryCommunityList(Set<String> orgNameSet) {
        InvokeCfg cfg = new InvokeCfg();
        cfg.setModuleKey(Constant.MODULE_KEY);
        cfg.setClassName(Constant.MODULE_CLASS_NAME);
        cfg.setFunName("queryCommunityList");
        Map<String,Object> map = new HashMap<>();
        cfg.setArgs(map);
        JsonResult result = businessDelegate.invoke(cfg);
        log.info("queryCommunityList: " + result.toString());
        List<OptionVo> communityList = new ArrayList<>();
        if (result.getSuccess()) {
            if (result.getData() == null) {
                return JsonResult.ok("success",communityList);
            }
            JSONObject jsonObj = JSONObject.parseObject(result.getData().toString());
            List<OptionVo> optionList = JSON.parseArray(jsonObj.get("data").toString(), OptionVo.class);
            log.info("======社区列表====={}============", optionList.toString());
            //筛选可以看的社区
            communityList = optionList.stream().filter(item ->
                    orgNameSet.contains(item.getName())).collect(Collectors.toList());
            return JsonResult.ok("success",communityList);
        }
        OptionVo option1 = new OptionVo("2-1", "一级组织名称1");
        OptionVo option2 = new OptionVo("2-2", "一级组织名称2");
        communityList.add(option1);
        communityList.add(option2);
        return JsonResult.ok("success",communityList);
    }

    @APCOSApiOperation(value = "queryBuildingList", description = "查询楼栋列表", infDict = "findLDBySQID",
            reqDemo = "{\"communityId\":\"社区ID\"}", respDemo = "{\"data\":[{\"id\":\"楼栋ID\",\"name\":\"楼栋名称\"}]}",
            infType = APCOSApiConstans.INF_TYPE_OTHER)
    @APCOSApiRequests({
            @APCOSApiRequest(name = "communityId", value = "社区ID", dict = "SQID",matchType = APCOSApiConstans.MATCH_TYPE_EQ,
                    keyType = APCOSApiConstans.KEY_TYPE_STR,fieldType = APCOSApiConstans.FIELD_TYPE_GN,required = true,
                    dataType = APCOSApiConstans.DATA_TYPE_STR,lenth = "50",remark = "社区ID"),
    })
    @APCOSApiResponses({
            @APCOSApiResponse(name = "data", value = "返回集合", dict = "LDList",
                    keyType = APCOSApiConstans.KEY_TYPE_LIST,fieldType = APCOSApiConstans.FIELD_TYPE_GN,
                    dataType = APCOSApiConstans.DATA_TYPE_ARR,remark = "返回集合"),
            @APCOSApiResponse(name = "data.id", value = "楼栋id", dict = "LDId",
                    keyType = APCOSApiConstans.KEY_TYPE_STR,fieldType = APCOSApiConstans.FIELD_TYPE_GN,
                    dataType = APCOSApiConstans.DATA_TYPE_STR,lenth = "50",remark = "楼栋id"),
            @APCOSApiResponse(name = "data.name", value = "楼栋名称", dict = "LDName",
                    keyType = APCOSApiConstans.KEY_TYPE_STR,fieldType = APCOSApiConstans.FIELD_TYPE_GN,
                    dataType = APCOSApiConstans.DATA_TYPE_STR,lenth = "50",remark = "楼栋名称"),
    })
    public JsonResult queryBuildingList(String communityId) {
        InvokeCfg cfg = new InvokeCfg();
        cfg.setModuleKey(Constant.MODULE_KEY);
        cfg.setClassName(Constant.MODULE_CLASS_NAME);
        cfg.setFunName("queryBuildingList");
        Map<String,Object> map = new HashMap<>();
        map.put("communityId",communityId);
        cfg.setArgs(map);
        JsonResult result = businessDelegate.invoke(cfg);
        log.info("queryBuildingList: " + result.toString());
        List<OptionVo> buildingList = new ArrayList<>();
        if (result.getSuccess()) {
            if (result.getData() == null) {
                return JsonResult.ok("success",buildingList);
            }
            JSONObject jsonObj = JSONObject.parseObject(result.getData().toString());
            List<OptionVo> optionList = JSON.parseArray(jsonObj.get("data").toString(), OptionVo.class);
            log.info("======楼栋列表====={}============", optionList.toString());
            return JsonResult.ok("success",optionList);
        }
        OptionVo option1 = new OptionVo("1", "楼栋1");
        OptionVo option2 = new OptionVo("2", "楼栋2");
        buildingList.add(option1);
        buildingList.add(option2);
        return JsonResult.ok("success",buildingList);
    }
}
